import UIKit
import Alamofire
import GradientLoadingBar
import SwiftEventBus

class HistoryViewController: UITableViewController {
    let notchGradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    
    var list:[History] = []
    let cellIdentifier = "history_cell"
    
    var pageTitle = "对话记录"
    var type = 0
    override func viewDidLoad() {
        
        super.viewDidLoad()
        navigationItem.title = pageTitle
        tableView.register(HistoryCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.backgroundColor = primaryDarkBackgroundColor
        notchGradientLoadingBar.fadeIn()
        getList()
        
        let okButton = UIBarButtonItem(title: "清空", style: .plain, target: self, action: #selector(handleokButtonClicked))
        navigationItem.rightBarButtonItem = okButton
    }
    
    
    @objc private func handleokButtonClicked() {
        
        let alertController = UIAlertController(title: "提示",
                                message: "确定要清空历史吗？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "清空", style: .default, handler: {
                    action in
                    
                    self.clearHistory()
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
    }
    
    func getList(){
        
        let parameters = HistoryParameters(type:type)
        AFManager.sharedInstance.manager.request("\(baseUrl)questions/getHistoryList",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            self.notchGradientLoadingBar.fadeOut()
            if let string = response.value{
                print(string)
                self.parseJson(json: string)
            }else{
                
            }
        }
    }
    
    func clearHistory(){
        notchGradientLoadingBar.fadeIn()
        let parameters = HistoryParameters(type:type)
        AFManager.sharedInstance.manager.request("\(baseUrl)questions/clear",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
            self.notchGradientLoadingBar.fadeOut()
            if let string = response.value{
                self.view.makeToast("删除成功",position: .center)
                self.list = []
                self.tableView.reloadData()
            }else{
                
            }
        }
    }
    
    func parseJson(json: String?){
        if let string = json{
            let data = Data(string.utf8)
            do {
                let jsonDecoder = JSONDecoder()
                let historyResponse = try jsonDecoder.decode(HistoryResponse.self, from: data)
                if !historyResponse.data.isEmpty{
                    list = historyResponse.data
                    self.tableView.reloadData()
                }else{
                    self.view.makeToast("暂无历史记录",position: .center)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5){
                        self.navigationController?.popViewController(animated: true)
                    }
                }
                
            } catch {
                print(error)
            }
        }
    }
    
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
           return [NSAttributedString.Key.foregroundColor: UIColor.white]
       }
    
   
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! HistoryCell
        cell.selectionStyle = .none
        cell.bindViewModel(list[indexPath.row])
        return cell
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UIPasteboard.general.string = list[indexPath.row].answer
        self.view.makeToast("复制成功",position: .center)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    
    
    
}
